﻿using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace CloudMailShared
{
    public class MailCloudStorage
    {
        private CloudStorageAccount StorageAccount { get; set; }
        public string ContainerName { get; private set; }

        private CloudBlobContainer mailStorageContainer = null;
        private CloudQueue mailQueue = null;

        /// <summary>
        /// Initializes a new instance of the <see cref="MailCloudStorage"/> class.
        /// Use this constructor to access the development fabric
        /// </summary>
        /// <param name="containerName">Name of the container.</param>
        public MailCloudStorage(string containerName)
        {
            StorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
            ContainerName = containerName;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MailCloudStorage"/> class.
        /// </summary>
        /// <param name="azureStorageId">The azure storage id.</param>
        /// <param name="containerName">Name of the container.</param>
        public MailCloudStorage(string azureStorageId, string containerName)
        {
            StorageAccount = CloudStorageAccount.Parse(azureStorageId);
            ContainerName = containerName;
        }

        /// <summary>
        /// Gets the blob storage container holding the mail messages.
        /// </summary>
        /// <value>The mail storage container.</value>
        public CloudBlobContainer MailStorageContainer
        {
            get
            {
                if (mailStorageContainer == null)
                {
                    CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient();
                    blobClient.GetContainerReference(ContainerName).CreateIfNotExist();
                    mailStorageContainer = blobClient.GetContainerReference(ContainerName);
                }

                return mailStorageContainer;
            }
        }

        /// <summary>
        /// Gets the queue holding references to the messages
        /// in blob storage
        /// </summary>
        /// <value>The mail queue.</value>
        public CloudQueue MailQueue
        {
            get
            {
                if (mailQueue == null)
                {
                    CloudQueueClient queueClient = StorageAccount.CreateCloudQueueClient();
                    queueClient.GetQueueReference(ContainerName).CreateIfNotExist();
                    mailQueue = queueClient.GetQueueReference(ContainerName);
                }

                return mailQueue;
            }
        }
    }
}
